package com.fight.util;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;

/**
* @ClassName: IPv4Util
* @Description: IPv4工具类
* @company:上海苏秦科技
* @author 温泉
* @date 2012-2-22
*/ 
public class IPv4Util {
	private final static int INADDRSZ = 4;

	
    /**
    * @Title: ipToBytesByInet
    * @Description: 把IP地址转化为字节数组
    * @author 温泉
    * @date 2012-2-22
    * @param ipAddr
    * @return byte[]    返回类型
    * @throws
    */ 
    public static byte[] ipToBytesByInet(String ipAddr) {
        try {
            return InetAddress.getByName(ipAddr).getAddress();
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }
    }


    /**
    * @Title: ipToBytesByReg
    * @Description: 把IP地址转化为int
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipAddr
    * @return byte[]    返回类型
    * @throws
    */ 
    public static byte[] ipToBytesByReg(String ipAddr) {
        byte[] ret = new byte[4];
        try {
            String[] ipArr = ipAddr.split("\\.");
            ret[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
            ret[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
            ret[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
            ret[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);
            return ret;
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }

    }

    /**
    * @Title: bytesToIp
    * @Description: 字节数组转化为IP
    * @author 温泉
    * @date 2012-2-22
    * @param  bytes
    * @return String    返回类型
    * @throws
    */ 
    public static String bytesToIp(byte[] bytes) {
        return new StringBuffer().append(bytes[0] & 0xFF).append('.').append(
                bytes[1] & 0xFF).append('.').append(bytes[2] & 0xFF)
                .append('.').append(bytes[3] & 0xFF).toString();
    }

    /**
    * @Title: bytesToInt
    * @Description: 根据位运算把 byte[] -> int
    * @author 温泉
    * @date 2012-2-22
    * @param @param bytes
    * @return int    返回类型
    * @throws
    */ 
    public static int bytesToInt(byte[] bytes) {
        int addr = bytes[3] & 0xFF;
        addr |= ((bytes[2] << 8) & 0xFF00);
        addr |= ((bytes[1] << 16) & 0xFF0000);
        addr |= ((bytes[0] << 24) & 0xFF000000);
        return addr;
    }

    /**
    * @Title: ipToInt
    * @Description: 把IP地址转化为int
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipAddr
    * @return int    返回类型
    * @throws
    */ 
    public static int ipToInt(String ipAddr) {
        try {
            return bytesToInt(ipToBytesByInet(ipAddr));
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }
    }

    /**
    * @Title: intToBytes
    * @Description: ipInt -> byte[]
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipInt
    * @return byte[]    返回类型
    * @throws
    */ 
    public static byte[] intToBytes(int ipInt) {
        byte[] ipAddr = new byte[INADDRSZ];
        ipAddr[0] = (byte) ((ipInt >>> 24) & 0xFF);
        ipAddr[1] = (byte) ((ipInt >>> 16) & 0xFF);
        ipAddr[2] = (byte) ((ipInt >>> 8) & 0xFF);
        ipAddr[3] = (byte) (ipInt & 0xFF);
        return ipAddr;
    }

    /**
    * @Title: intToIp
    * @Description: 把int->ip地址
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipInt
    * @return String    返回类型
    * @throws
    */ 
    public static String intToIp(int ipInt) {
        return new StringBuilder().append(((ipInt >> 24) & 0xff)).append('.')
                .append((ipInt >> 16) & 0xff).append('.').append(
                        (ipInt >> 8) & 0xff).append('.').append((ipInt & 0xff))
                .toString();
    }

    
    
    /**
    * @Title: getIPIntScope
    * @Description: 把192.168.1.1/24 转化为int数组范围
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipAndMask
    * @return int[]    返回类型
    * @throws
    */ 
    public static int[] getIPIntScope(String ipAndMask) {

        String[] ipArr = ipAndMask.split("/");
        if (ipArr.length != 2) {
            throw new IllegalArgumentException("invalid ipAndMask with: "
                    + ipAndMask);
        }
        int netMask = Integer.valueOf(ipArr[1].trim());
        if (netMask < 0 || netMask > 31) {
            throw new IllegalArgumentException("invalid ipAndMask with: "
                    + ipAndMask);
        }
        int ipInt = IPv4Util.ipToInt(ipArr[0]);
        int netIP = ipInt & (0xFFFFFFFF << (32 - netMask));
        int hostScope = (0xFFFFFFFF >>> netMask);
        return new int[] { netIP, netIP + hostScope };

    }


    /**
    * @Title: getIPAddrScope
    * @Description: 把192.168.1.1/24 转化为IP数组范围
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipAndMask
    * @return String[]    返回类型
    * @throws
    */ 
    public static String[] getIPAddrScope(String ipAndMask) {
        int[] ipIntArr = IPv4Util.getIPIntScope(ipAndMask);
        return new String[] { IPv4Util.intToIp(ipIntArr[0]),
                IPv4Util.intToIp(ipIntArr[0]) };
    }

    
    
    /**
    * @Title: getIPIntScope
    * @Description: 根据IP 子网掩码（192.168.1.1 255.255.255.0）转化为IP段
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipAddr
    * @param @param mask
    * @return int[]    返回类型
    * @throws
    */ 
    public static int[] getIPIntScope(String ipAddr, String mask) {

        int ipInt;
        int netMaskInt = 0, ipcount = 0;
        try {
            ipInt = IPv4Util.ipToInt(ipAddr);
            if (null == mask || "".equals(mask)) {
                return new int[] { ipInt, ipInt };
            }
            netMaskInt = IPv4Util.ipToInt(mask);
            ipcount = IPv4Util.ipToInt("255.255.255.255") - netMaskInt;
            int netIP = ipInt & netMaskInt;
            int hostScope = netIP + ipcount;
            return new int[] { netIP, hostScope };
        } catch (Exception e) {
            throw new IllegalArgumentException("invalid ip scope express  ip:"
                    + ipAddr + "  mask:" + mask);
        }

    }

    /**
    * @Title: getIPStrScope
    * @Description: 根据IP 子网掩码（192.168.1.1 255.255.255.0）转化为IP段
    * @author 温泉
    * @date 2012-2-22
    * @param @param ipAddr
    * @param @param mask
    * @return String[]    返回类型
    * @throws
    */ 
    public static String[] getIPStrScope(String ipAddr, String mask) {
        int[] ipIntArr = IPv4Util.getIPIntScope(ipAddr, mask);
        return new String[] { IPv4Util.intToIp(ipIntArr[0]),IPv4Util.intToIp(ipIntArr[0]) };
    }

    /**
     * @Title: getIpAddr
     * @Description: 从request中获取ip
     * @param @param request
     * @param @return 设定文件
     * @return String 返回类型
     * @author: 韩欣宇
     * @date 2013-10-08 15:11:36 +0800
     * @throws
     */
    public static String getIpAddrFromRequest(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }
   /**
    * @Title: isJurisdiction
    * @Description: TODO(判断访问的ip是否有访问的权限)
    * @param @param ipList
    * @param @param request
    * @param @return    设定文件
    * @return boolean    返回类型
    * @author: 阮启伟
    * @date 2015年12月24日 下午1:22:17
    * @throws
    */
    public static boolean isJurisdiction(String []ipList,HttpServletRequest request){
		boolean flag = false;
		String ip = IPv4Util.getIpAddrFromRequest(request);
		if (ipList != null && ipList.length > 0) {
			for (int j = 0; j < ipList.length; j++) {
				if (ip.equals(ipList[j])) {
					flag = true;
				}
			}
		}
		return flag;
	}
}
